<?php

namespace app\zyhsapi\controller\v2;

use app\common\lib\Aes;
use app\common\lib\exception\ApiException;
use app\common\lib\IAuth;
use app\common\lib\Util;
use app\zyhsapi\controller\ZyhsAuth;
use app\zyhsapi\model\ZyhsLoginLog;
use app\zyhsapi\model\ZyhsRecode;
use app\zyhsapi\model\ZyhsUser;
use app\zyhsapi\model\ZyhsUserCoupon;
use app\zyhsapi\service\JiGuang;
use app\zyhsmarketing\service\MarketingCallback;
use think\Log;
use think\response\Json;

class Login extends ZyhsAuth
{
    /**
     * 手机号一键登录
     * @return Json
     */
    public function phoneOneClick()
    {
        $loginToken = input('login_token/s');
        $time = $this->request->time();
        $ip = $this->request->ip();
        $appConfig = config('zyhsapp');
        $telResData = (new JiGuang())->JGtokenGetMobile($loginToken);
        if ($telResData['success'])
        {
            $tel = $telResData['mobile'];
            //准币测试号
            if (isset($appConfig['coin_mobile'][$tel]) && $appConfig['coin_mobile'][$tel] === 2)
            {
                return show(config('code.error'), '该账号禁止登录');
            }
            $user = $this->CheckUserTel($tel, 86);
            // 生成token  和 token到期时间
            $token = IAuth::setAppLoginToken($tel);
            $data = [
                'token' => $token,
                'token_expire' => strtotime("+" . $appConfig['login_time_out_day'] . " days"),
            ];
            $UserModel = new ZyhsUser();
            //判断用户是否绑定准了号
            if ($user)
            {
                $UserModel->check_uen($user);
            }
            $nickname = preg_replace('/^([\w-]{3})([\w]*)([0-9]{4}$)/i', '$1****$3', $tel);
            $isRegister = false;
            // 该用户是否正常  forbidden==1 禁止登录
            if ($user && $user['forbidden'] == 0)
            {
                // 已过期重新生成access_token
                if ($time > $user['token_expire'] || !in_array($tel, $appConfig['mobile']))
                {
                    $UserModel->save($data, ['tel' => $tel]);
                } else
                {
                    $token = $user['token'];
                }
                if (!$user['nickname'])
                {
                    try
                    {
                        $UserModel->where('tel', $tel)->update(['nickname' => $nickname]);
                    }
                    catch (\think\Exception $e)
                    {
                        Log::write('手机验证码登陆时初始化用户昵称失败' . $e->getMessage(), true);
                    }
                }
            } elseif ($user && $user['forbidden'] == 1)
            {
                return show(config('code.error'), '该账号禁止登录');
            } //手机号不可注册
            elseif (!$user && !empty($tel))
            {
                $isRegister = true;
                $checkResult = Util::ZyhsRegistCheckLogoutCD(['tel' => $tel]);
                if (!$checkResult['result'])
                {
                    return show(config('code.error'), $checkResult['msg']);
                }
                // 第一次登录 注册数据
                $user['uen'] = substr(md5($this->request->time(true) . mt_rand(0, 1000000) . uniqid()), 0, 12);
                $user['nickname'] = $nickname;
                $user['reg_time'] = $time;
                $user['reg_ip'] = $ip;
                $user['last_login'] = $time;
                $user['last_ip'] = $ip;
                $user['last_active'] = $time;
                $user['status'] = 1;
                $user['sex'] = 1;
                $user['tel'] = $tel; // 国内手机号不拼接国际手机区号
                $user['is_first_login'] = 1;
                $user['uc_id'] = uuid($tel . microtime());
                $user['token'] = $data['token'];
                $user['token_expire'] = $data['token_expire'];
                $user['has_self_recode'] = 0;
                $user['channel'] = Util::getChannelId();
                try
                {
                    $user['id'] = $UserModel->insertGetId($user);
                    // 发送 注册 优惠券
                    (new ZyhsUserCoupon())->regUserSendBenefits($user['id']);
                }
                catch (\Exception $e)
                {
                    return show(config('code.error'), '注册失败,请稍后重试');
                }
            }

            if ($user)
            {
                $id = (int)($user['id']);
                if ($isRegister)
                {   // 绑定成功 查看手机号是否
                    $syncRecodeInfo = (new ZyhsRecode())->getAccountRecodeNumByTelZyhs($tel, $id);
                    if (!Util::IsIos()) // 安卓设备 打点回传
                    {   // 回传打点
                        $oaid = $this->headers['oaid'] ?? '';
                        $mobileType = input('mobile_type/d', 0);
                        (new MarketingCallback())->uploadActiveData($oaid, $id, 2, $mobileType);
                    }
                }
                // 获取自己档案ID
                $recordInfo = (new ZyhsRecode())->getRecodeLists($id, 1);
                $result = [
                    'id' => $id,
                    'self_rid' => $recordInfo ? (int)($recordInfo['id'] ?? 0) : 0,
                    'user_access_token' => (new Aes())->encryptWithOpenssl($token . "||" . $user['id'], 'zyhsapp'),
                    'has_bind_tel' => 1,     // 是否绑定了手机号 1绑定了 0未绑定
                    'sync_recode_info' => $syncRecodeInfo ?? [],
                    'is_register' => $isRegister ? 1 : 0,   // ----打点添加
                    'uen' => $user['uen'],   // ----打点添加
                    'tel' => $tel,   // ----打点添加
                ];
                // 记录登陆日志
                (new ZyhsLoginLog())->SaveData([
                    'uid' => $id,
                    'login_time' => $time,
                    'login_type' => 4,
                    'login_ip' => $ip,
                ]);

                $UserModel->removeUserCache($id);

                return show(config('code.success'), 'ok', $result);
            }
        } else
        {
            return show(411, '一键登录失败');
        }
    }
}
